<template>
  <Card :bordered="false" dis-hover>
    <Modal
      v-model="modalStatus"
      :loading="modalLoading"
      :title="modalTitle"
      width="800"
      @on-ok="saveUser"
    >
      <Form ref="form" :model="record" show-message :label-width="140">
        <FormItem label="角色名称：" prop="roleName" :rules="rules">
          <Input v-model="record.roleName" />
        </FormItem>
      </Form>
    </Modal>
    <Modal
      width="600"
      class-name="treeModal"
      v-model="menusTreeStatus"
    >
      <div slot="header" class="distHeader">
        <p>{{menusTreeTitle}}</p>
        <Spin v-if="distLoading">
          <Icon type="ios-loading" size=18 class="demo-spin-icon-load"></Icon>
        </Spin>
      </div>
      <Spin v-if="menusTreeLoading" fix></Spin>
      <Tree ref="tree" show-checkbox check-directly :data="roleMenusTree" @on-check-change="treeCheckChange" @on-contextmenu="contextData = $event">
        <template slot="contextMenu">
            <DropdownItem @click.native="handleContextMenuButton" style="color: #2d8cf0">按钮权限分配</DropdownItem>
        </template>
      </Tree>
      <div slot="footer">
          <Button type="primary" ghost @click="exchangeTree">{{treeOpenTitle}}</Button>
          <Button type="primary" @click="menusTreeStatus = false">关闭</Button>
      </div>
    </Modal>
    <Modal v-model="roleButton" title="分配按钮权限" :styles="{top: '300px'}">
      <div slot="header" class="distHeader">
        <p>分配按钮权限</p>
      </div>
      <Table border :loading="buttonLoading" :columns="modalButtonColumns" :data="modalButtonList">
        <template slot-scope="{ row }" slot="select">
          <Checkbox v-model="row.checked" @on-change="changeButtonRole($event,row)"></Checkbox>
        </template>
      </Table>
      <div slot="footer">
          <Button type="primary" @click="roleButton = false">关闭</Button>
      </div>
    </Modal>
    <Form ref="formFilter" :model="queryParams" class="edit-model-form" :label-width="100">
      <Row>
        <Col :xs="24" :sm="24" :md="12" :lg="6">
          <FormItem label="角色名称：">
            <Input placeholder="请输入角色名称" v-model="queryParams.roleName" clearable />
          </FormItem>
        </Col>
        <Col :xs="20" :sm="20" :md="20" :lg="6">
          <FormItem :label-width="20">
            <Button type="primary" @click="handleQuery">查询</Button>&nbsp;
            <Button type="primary" @click="resetQuery()">重置</Button>&nbsp;
            <Button type="success" @click="view()" v-if="pageButton.includes('add')">新增</Button>
          </FormItem>
        </Col>
          <table-extend :columns="columns" :queryParams="queryParams" @changeTableColumns="columns = $event" @changeTableSize="tableSize = $event"></table-extend>
      </Row>
    </Form>

    <div class="content">
      <Table :loading="loading" :columns="columns" :data="data" :size="tableSize">
        <template slot-scope="{ row, index }" slot="action">
          <Button type="primary" style="margin-right: 8px" @click="view(index, row)" v-if="pageButton.includes('edit')">编辑</Button>
          <Button type="error" style="margin-right: 8px" @click="doDelete(index, row)"  v-if="pageButton.includes('delete')">删除</Button>
          <Button type="info" @click="roleMenus(index, row)" v-if="pageButton.includes('access')">权限分配</Button>
        </template>
      </Table>
        <Page
          min-hidden
          slot="footer"
          :current="queryParams.pageNo"
          :total="total"
          :page-size="queryParams.pageSize"
          show-total
          @on-change="changePage"
          @on-page-size-change="changepageSize"
          :page-size-opts="[10, 20, 30]"
          show-elevator
          show-sizer
        ></Page>
        <Page min-show slot="footer" :current="queryParams.pageNo" :total="total" simple />
    </div>
  </Card>
</template>

<script>
import { getRoleList, addRole, editRole, delRole, getRoleMenu, updateRoleMenu, getRoleButtons, updateRoleButton } from "@/api/role";
import mixins from "@/mixins";
export default {
  name: "role",
  mixins: [mixins],
  data() {
    return {
      rules: {required: true, message: '角色名称不能为空', trigger: 'change,blur'},
      columns: [
        {
          title: "",
          width: 80,
          align: "center",
          render: (h, params) => {
            return h("span", params.index + (this.queryParams.pageNo - 1) * this.queryParams.pageSize + 1);
          }
        },
        {
          title: "角色名称",
          minWidth: 120,
          key: "roleName"
        }
      ],
      menusTreeLoading: false,
      menusTreeStatus: false,
      menusTreeTitle: null,
      roleId: null,
      distLoading: false,
      treeOpenStatus: true,
      roleMenusTree: [],
      
      modalButtonColumns: [
        {
            width: 60,
            slot: 'select'
        },
        {
          title: "按钮Key",
          key: "buttonKey"
        },
        {
          title: "按钮名称",
          key: "buttonName"
        }
      ],
      
      contextData: {},
      modalButtonList: [],
      roleButton: false,
      buttonLoading: false
    };
  },
  created() {
    this.getList();
  },
  computed: {
    treeOpenTitle() {
      return this.treeOpenStatus ? "全部收起" : "全部展开"
    },
    pageButton() {
      let pageButton = this.$store.state.router.pageButton;
      (pageButton.includes('edit') || pageButton.includes('delete') || pageButton.includes('access')) && this.columns.push({
        title: "操作",
        minWidth: 180,
        slot: "action"
      })
      return pageButton;
    }
  },
  methods: {
    getList() {
      this.loading = true;
      getRoleList(this.queryParams).then(res => {
        this.data = res.data;
        this.total = res.total;
      }).finally(()=>{this.loading = false});
    },
    // 编辑弹窗
    view(index, row) {
      this.$refs.form.resetFields();
      row ? (this.modalTitle = "编辑角色") : (this.modalTitle = "新增角色");
      this.modalStatus = true;
      this.record = { ...row };
    },
    // 过滤菜单
    filterMenu(tree = []) {
      let arr = [];
      if (tree.length !== 0) {
          tree.forEach(item => {
            let obj = item;
            obj.title = obj.name;
            obj.expand = true;
            obj.contextmenu = true;
            if (item.children && item.children.length != 0) {
                obj.children = this.filterMenu(item.children);
            }
            arr.push(obj);
          });
      }
      return arr;
    },
    // 分配某个角色权限获取菜单
    roleMenus(index, row) {
      this.menusTreeLoading = true;
      this.menusTreeStatus = true;
      this.menusTreeTitle = `分配 ${row.roleName} 的权限`;
      this.roleId = row.id;
      getRoleMenu({
        roleId: this.roleId
      }).then(res => {
        this.roleMenusTree = this.filterMenu(res.data);
      }).finally(()=>{this.menusTreeLoading = false});
    },
    treeCheckChangeFilter(tree = []) {
       return this.$refs.tree.getCheckedAndIndeterminateNodes().reduce((arr, item) => {
        arr.push(item.id);
        return arr
      }, [])
      // // 无半选中
      // let menuArr = [];
      // tree.forEach(item => {
      //   item.checked && !item.children && menuArr.push(item.id);
      //   if (item.children && item.children.length != 0) menuArr.push(...this.treeCheckChangeFilter(item.children));
      // })
      // return menuArr;
    },
    // 复选框选择选中/取消
    treeCheckChange(e) {
      // console.log(this.treeCheckChangeFilter(this.roleMenusTree))
      updateRoleMenu({
        roleId: this.roleId,
        roleList: this.treeCheckChangeFilter()
      }).then(res => {
        
      })
    },
    // 全部收起/展开
    exchangeTree() {
      this.roleMenusTree = this.treeChangeExpand(this.roleMenusTree, this.treeOpenStatus =! this.treeOpenStatus);
    },
    //递归给树设置某一项
    treeChangeExpand(treeData, flag) {
      let _this = this;
      for (var i = 0; treeData && i < treeData.length; i++) {
        treeData[i].expand = flag;
        if (treeData[i].children) {
          treeData[i].children = _this.treeChangeExpand(treeData[i].children, flag);
        }
      }
      return treeData;
    },
    // 保存角色信息
    saveUser() {
      this.$refs.form.validate((valid) => {
        if(valid) {
          this.modalLoading = true
          let addOrUpDate = this.record.id ? editRole : addRole;
          // [this.record.id ? editUser(this.record) : addUser(this.record)].then(res => {
          addOrUpDate(this.record).then(res => {
            this.getList();
            this.$Message.success(this.record.id ? "编辑成功" : "新增成功");
          }).finally(()=>this.modalStatus = false);
        } else {
          this.$Message.warning("校验未通过");
          this.modalLoading = false;
          this.$nextTick(() => {
            this.modalLoading = true;
          });
        }
      });
    },
    // 删除角色
    doDelete(index, row) {
      this.modalConfirm("确定要删除吗？", () => {
        delRole({ roleId: row.id }).then((res) => {
          this.getList();
          this.$Message.success("删除成功");
        });
      })
    },
    // 按钮权限列表
    handleContextMenuButton() {
      this.roleButton = true;
      this.buttonLoading = true;
      getRoleButtons({
        roleId: this.roleId,
        menuId: this.contextData.id
      }).then(res=>{
        this.modalButtonList = res.data;
        this.buttonLoading = false;
      }).finally(()=>{this.buttonLoading=false})
    },
    // 按钮权限分配
    changeButtonRole(flag, row) {
      this.buttonLoading = true;
      updateRoleButton({
        roleId: this.roleId,
        menuId: this.contextData.id,
        buttonKey: row.buttonKey,
        checked: flag ? 1 : 0
      }).finally(()=>{this.buttonLoading=false})
    }
  }
};
</script>
<style lang="less" scoped>
.demo-spin-icon-load{
    animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
    from { transform: rotate(0deg);}
    50%  { transform: rotate(180deg);}
    to   { transform: rotate(360deg);}
}
</style>